package ch6.pool;

import tools.SleepTools;

import java.util.Random;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author LuHuanCheng
 * 类说明：线程池里面的任务设置为守护线程  主线程结束了  线程池里面的任务也跟着结束不再执行
 */
public class ThreadPoolAdv {


    public static void main(String[] args) {
        ExecutorService threadPoolExecutor = new ThreadPoolExecutor(2, 4,
                3, TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(10), new MyThreadFactory(),new ThreadPoolExecutor.AbortPolicy());

        for (int i = 0; i <= 6; i++) {
            Worker worker = new Worker("worker" + i);
            System.out.println("主线程a new task has been added：" + worker.getName());
            threadPoolExecutor.execute(worker);
        }
    }

    //自定义线程，这里用作任务
    private static class Worker implements Runnable {
        private String taskName;
        private Random r = new Random();

        public Worker(String taskName) {
            this.taskName = taskName;
        }

        public String getName() {
            return taskName;
        }

        @Override
        public void run() {
            System.out.println("自定义线程" + Thread.currentThread().getName() + " process the task : " + taskName);
            SleepTools.ms(r.nextInt(100) * 5);
        }
    }

    //自定义ThreadFactory
    private static class MyThreadFactory implements ThreadFactory {

        private AtomicInteger count = new AtomicInteger(0);

        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread("lhc" + count.getAndIncrement());
            thread.setDaemon(true);
            System.out.println("自定义ThreadFactory创建线程：" + thread);
            return thread;
        }
    }
}